package com.pine.dbant.plugin.sqlite.function;

import com.pine.dbant.common.jdbc.JdbcUtils;
import com.pine.dbant.common.model.JdbcMetadataTreeView;
import com.pine.dbant.common.plugin.meta.*;
import com.pine.sunflower.core.utils.Strings;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class SqliteTablesFunction extends AbstractQueryMetadataFunction<JdbcMetadataAnalysisConfig, List> {

    public SqliteTablesFunction(String type) {
        super(type);
    }

    @Override
    public List<MetadataNode> doQuery(JdbcMetadataAnalysisConfig metadataAnalysisConfig, QueryMetadataParam queryMetadataParam) {
        String catalog = queryMetadataParam.getConfiguration().getNecessaryValue("catalog");
        String sql = "select * from sqlite_master where type='table'";
        List<Map<String, Object>> result = JdbcUtils.getSqlRunner(metadataAnalysisConfig.getConnection()).queryList(sql);
        List<MetadataNode> metadataNodes = new ArrayList<>();
        result.forEach(map -> {
            String tableName = String.valueOf(map.get("name"));
            metadataNodes.add(new DefaultMetadataNode()
                    .setName(tableName)
                    .setId(Strings.format("{}_{}_{}", metadataAnalysisConfig.getConnectionInfo().getId(), catalog, tableName))
                    .setType(JdbcMetadataTreeView.TABLE.getType())
                    .setLeaf(true)
                    .addProperties(map)
                    .addProperty(CONN_ID, metadataAnalysisConfig.getConnectionInfo().getId())
                    .addProperty(CATALOG, catalog));
        });
        return metadataNodes;
    }
}
